package com.second.oa.web.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.second.oa.domain.Employee;
import com.second.oa.domain.Power;
import com.second.oa.exception.LoginException;
import com.second.oa.service.EmployeeService;
import com.second.oa.service.PowerService;
import com.second.oa.service.impl.EmployeeServiceImpl;
import com.second.oa.service.impl.PowerServiceImpl;


public class LoginServlet extends HttpServlet {

	/**
	 * 员工信息服务对象
	 */
	private EmployeeService employeeService = new EmployeeServiceImpl();
	/**
	 * 权限信息服务对象
	 */
	private PowerService powerService = new PowerServiceImpl();
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String code = request.getParameter("code");
		String password = request.getParameter("password");
		
		try {
			Employee emp = employeeService.login(code, password);
			Set<Power> powers = powerService.getPowerByEmp(emp);
			
			// 将登陆信息保存到session中
			HttpSession session = request.getSession();
			emp.setPassword(null);
			session.setAttribute("current", emp);
			session.setAttribute("powers", powers);
						
			// 登陆成功
			response.sendRedirect(request.getContextPath() + "/index.jsp");
		} catch (LoginException e) {
			e.printStackTrace();
			
			request.setAttribute("msg", e.getMessage());
			// 登陆失败
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}
